package com.ik.hiddevice;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.ik.hiddevice.listener.OnBlueScanListener;
import com.ik.hiddevice.listener.OnBondStateChanedListener;
import com.ik.hiddevice.utlis.ClsUtils;
import com.ik.hiddevice.utlis.LogUtil;

public class BlueToothHelper {
    private static final String TAG = "BlueToothHelper";
    private static final String DEVICE_NAME = "RED Control";
    private BroadcastReceiver mBluetoothStateReceiver;
    private BroadcastReceiver mBluetoothScanResultReceiver;
    private BroadcastReceiver mBondReceiver;
    private OnBlueScanListener onBlueScanListener;
    private OnBondStateChanedListener onBondStateChanedListener;

    public void setOnBlueScanListener(OnBlueScanListener onBlueScanListener) {
        this.onBlueScanListener = onBlueScanListener;
    }

    public void removeOnBlueScanListener(Context context){
        if (null != mBluetoothScanResultReceiver){
            context.unregisterReceiver(mBluetoothScanResultReceiver);
            mBluetoothScanResultReceiver = null;
        }
        if (null !=onBlueScanListener){
            onBlueScanListener = null;
        }
    }

    public void setOnBondStateChanedListener(OnBondStateChanedListener onBondStateChanedListener) {
        this.onBondStateChanedListener = onBondStateChanedListener;
    }
    public void removeOnBondStateChanedListener(Context context){
        if (null != mBondReceiver){
            context.unregisterReceiver(mBondReceiver);
            mBondReceiver = null;
        }
        if (null != onBondStateChanedListener){
            onBondStateChanedListener = null;
        }
    }
    public void start(final Context context, final BluetoothAdapter bluetoothAdapter){
        if (!bluetoothAdapter.isEnabled()) {
            LogUtil.showLogD( TAG,"蓝牙没有打开");
            if (mBluetoothStateReceiver == null) {
                mBluetoothStateReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        LogUtil.showLogD(TAG,"蓝牙广播："+intent.getAction());
                        if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                BluetoothAdapter.STATE_OFF) == BluetoothAdapter.STATE_ON) {
                            LogUtil.showLogD(TAG,"蓝牙已打开");
                            start(context,bluetoothAdapter);
                        } else {
                            LogUtil.showLogD(TAG,"蓝牙尚未启动，已广播： ");
                        }
                    }
                };
                context.registerReceiver(mBluetoothStateReceiver,
                        new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
            }
            bluetoothAdapter.enable();
        } else {
            if (mBluetoothStateReceiver != null) {
                context.unregisterReceiver(mBluetoothStateReceiver);
                mBluetoothStateReceiver = null;
            }
            startScan(context,bluetoothAdapter);
        }

    }
    public void startScan(Context context,BluetoothAdapter bluetoothAdapter){
        if (mBluetoothScanResultReceiver==null){
            mBluetoothScanResultReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    LogUtil.showLogD(TAG,"蓝牙广播："+action);
                    if (TextUtils.equals(action,BluetoothDevice.ACTION_FOUND)){
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        if (null != onBlueScanListener && null != device && TextUtils.equals(DEVICE_NAME,device.getName()) ){
                            onBlueScanListener.onDeviceFound(device);
                        }
                    }else if (TextUtils.equals(action,BluetoothAdapter.ACTION_DISCOVERY_STARTED)){
                        if (null != onBlueScanListener){
                            onBlueScanListener.onScanStarted();
                        }
                    }else if (TextUtils.equals(action,BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                        if (null != onBlueScanListener){
                            onBlueScanListener.onScanFinished();
                        }
                    }
                }
            };
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        context.registerReceiver(mBluetoothScanResultReceiver, filter);
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
    }

    public void pair(Context context,BluetoothDevice device){
        if (null == mBondReceiver){
            mBondReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    LogUtil.showLogD(TAG,"蓝牙广播："+intent.getAction());
                    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())){
                        BluetoothDevice extra_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
                                BluetoothDevice.BOND_NONE);
                        int previousBondState = intent.getIntExtra(
                                BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.BOND_NONE);
                        if (device.equals(extra_device)){
                            if (null != onBondStateChanedListener){
                                onBondStateChanedListener.onBondStateChanged(extra_device,previousBondState,bondState);
                            }
                        }
                    }else if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(intent.getAction())){
                        BluetoothDevice extra_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        LogUtil.showLogE(TAG,"ACTION_ACL_DISCONNECTED");
                    }else if(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(intent.getAction())){
                        BluetoothDevice extra_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        LogUtil.showLogE(TAG,"ACTION_ACL_DISCONNECT_REQUESTED");
                    }else if (BluetoothDevice.ACTION_NAME_CHANGED.equals(intent.getAction())){
                        BluetoothDevice extra_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        LogUtil.showLogE(TAG,"ACTION_NAME_CHANGED");
                    }else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(intent.getAction())){
                        BluetoothDevice extra_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        LogUtil.showLogE(TAG,"ACTION_ACL_CONNECTED");
                    }else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(intent.getAction())){

                        BluetoothDevice extra_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
                                BluetoothAdapter.STATE_DISCONNECTED);
                        LogUtil.showLogE(TAG,"连接状态：【"+extra_device.getName()+"】state："+state);
                        switch (state){
                            case BluetoothAdapter.STATE_DISCONNECTED:
                            case BluetoothAdapter.STATE_CONNECTING:
                            case BluetoothAdapter.STATE_CONNECTED:
                            case BluetoothAdapter.STATE_DISCONNECTING:
                        }

                    }

                }
            };
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        /*
         *ACL用于分组数据传送(还有个SCO是用于同步话音传送)
         *设备已链接（值得注意的是，配对过程中系统会发送这个广播，
         * 但这个时候只是处于配对过程并不是已经可以链接并通讯的状态，所以不能以这个为准是否已经可以通讯）
         */
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_NAME_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        context.registerReceiver(mBondReceiver, filter);
        LogUtil.showLogE(TAG,"执行绑定："+device.createBond());
    }

    public void connect(Context context,BluetoothDevice device,BluetoothAdapter bluetoothAdapter){
        if (!bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceDisconnected(int profile) {
                LogUtil.showLogD( TAG,"服务连接断开");
                closeProfileProxy(bluetoothAdapter);
            }

            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                mHidProxy = proxy;
                if (device != null) {
                    ClsUtils.connect(proxy,device);
                    ClsUtils.setPriority(proxy,device,1000);
                }
            }
        }, 4)) {
           LogUtil.showLogD(TAG,"连接失败");
        }
    }
    BluetoothProfile mHidProxy;
    void closeProfileProxy(BluetoothAdapter bluetoothAdapter) {
        if (mHidProxy != null) {
            try {
                bluetoothAdapter.closeProfileProxy(4, mHidProxy);
                mHidProxy = null;
            } catch (Throwable t) {
                LogUtil.showLogD(TAG, "清除输入配置文件代理时出错"+t.getMessage());
            }
        }
    }
}
